import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

class QrCodeResult {
  bool success;
  String result;
  // 是否主动关闭扫码页面
  bool closeScanPage;

  QrCodeResult({this.success = false, this.result = '', this.closeScanPage = true});
}

final qrCodeProvider = StateProvider<QrCodeResult>((ref) {
  return QrCodeResult();
});

class BindDevicePage extends ConsumerStatefulWidget {
  const BindDevicePage({super.key});

  @override
  ConsumerState<BindDevicePage> createState() => _BindDevicePageState();
}

class _BindDevicePageState extends ConsumerState<BindDevicePage> {
  final TextEditingController _imeiController = TextEditingController();
  final GlobalKey _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _imeiController.dispose();
    super.dispose();
  }

  _addDevice() async {
    final postData = {
      'imei': _imeiController.text,
    };
    ToastUtils.showLoading();
    final res = await post<BaseResp, BaseResp>('/device/bind', data: postData, decodeType: BaseResp());
    res.when(success: (BaseResp resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果当前没有设备，则切换到该设备
        final deviceInfo = ref.read(deviceInfoProvider);
        if (deviceInfo.imei == null) {
          ToastUtils.showToast('绑定成功');
          ToastUtils.showLoading();
          ref.read(deviceInfoProvider.notifier).switchImei(_imeiController.text, () {
            Future.delayed(const Duration(milliseconds: 1000), () {
              ToastUtils.dismissLoading();
              context.go('/');
            });
          });
          return;
        }
        // 当前有设备的情况下，弹窗提示
        showDialog(
            context: context,
            builder: (context) {
              return CupertinoAlertDialog(
                title: const Text('绑定成功'),
                content: const Text('设备绑定成功，是否立即切换到该设备？'),
                actions: [
                  TextButton(
                    onPressed: () {
                      context.pop();
                    },
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () {
                      final imei = _imeiController.text;
                      context.pop();
                      ToastUtils.showLoading();
                      // 切换设备
                      ref.read(deviceInfoProvider.notifier).switchImei(imei, () {
                        ToastUtils.dismissLoading();
                        this.context.go('/');
                      });
                      _imeiController.clear();
                    },
                    child: const Text('确定'),
                  ),
                ],
              );
            });
      } else {
        ToastUtils.showToast(resp.msg ?? '绑定失败');
      }
    }, failure: (String msg, int code) {
      XLogger.debug('绑定失败：msg: $msg, code: $code');
    });
  }

  _scanQrCodeFinish() {
    XLogger.debug('扫码完成');
    // 获取扫码结果
    final qrCodeResult = ref.watch(qrCodeProvider);
    if (qrCodeResult.closeScanPage) {
      return;
    }
    // 如何扫码成功，弹窗询问是否绑定设备
    if (qrCodeResult.success) {
      _imeiController.text = qrCodeResult.result;
      showCupertinoDialog(
          context: context,
          builder: (context) {
            return CupertinoAlertDialog(
              title: const Text('扫码成功'),
              content: const Text('是否绑定该设备？'),
              actions: [
                TextButton(
                  onPressed: () {
                    context.pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    context.pop();
                    _addDevice();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          });
    } else {
      ToastUtils.showToast('扫码失败，请重试');
    }
  }

  _onScanBtnClick() async {
    var status = await Permission.camera.status;
    XLogger.debug('status: $status');
    if (Platform.isAndroid) {
      if (status.isDenied || status.isPermanentlyDenied) {
        PermissionManager.requestPermissionDialog(context, msg: '为了扫描设备码，我们需要您的许可来使用相机。请允许访问相机以便继续。',
            confirmAction: () async {
          var statusNew = await Permission.camera.request();
          if (statusNew.isGranted) {
            _goScanPage();
          } else {
            ToastUtils.showToast('请允许访问相机以便继续');
          }
        },cancelAction: () async{
              context.pop();

            });


        return;
      }
    }
    _goScanPage();
  }

  _goScanPage() async {
    ref.read(qrCodeProvider.notifier).state = QrCodeResult();
    await context.push(RouterManager.scanQrCode);
    _scanQrCodeFinish();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "添加设备",
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        foregroundColor: Colors.white,
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            // 输入框
            Container(
              margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
              // height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
              ),
              child: TextFormField(
                controller: _imeiController,
                maxLines: 1,
                keyboardType: TextInputType.number,
                textAlignVertical: TextAlignVertical.center,
                decoration: InputDecoration(
                  hintText: '请输入设备IMEI号',
                  hintStyle: TextStyle(
                    fontSize: 14,
                    color: AppTheme.themeConfig.secondaryTextColor,
                  ),
                  border: InputBorder.none,
                  contentPadding: const EdgeInsets.only(left: 10, right: 50),
                  // 是否使用更小的高度
                  isDense: true,
                  // // 右侧扫码图标
                  suffixIcon: IconButton(
                      // 点击时的颜色
                      splashColor: Colors.transparent,
                      onPressed: () async {
                        _onScanBtnClick();
                      },
                      icon: Icon(
                        Icons.qr_code_scanner,
                        color: AppTheme.themeConfig.secondaryTextColor,
                        size: 20,
                      )),
                ),
                // 校验，设备号不能为空，且为11或者12位数字
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '设备号不能为空';
                  }
                  if (value.length != 11 && value.length != 12) {
                    return '设备号长度不正确';
                  }
                  return null;
                },
              ),
            ),
            // 提示
            Container(
              margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
              child: Text(
                'IMEI号在设备背面贴纸上',
                style: TextStyle(
                  fontSize: 12,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
              ),
            ),
            // 添加按钮
            Container(
              margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
              height: 50,
              width: 120,
              decoration: BoxDecoration(
                color: AppTheme.themeConfig.primaryColor,
                borderRadius: BorderRadius.circular(25),
              ),
              child: TextButton(
                onPressed: () {
                  // 校验表单
                  if ((_formKey.currentState as FormState).validate()) {
                    _addDevice();
                  }
                },
                child: const Text(
                  '添加',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
